/*
 * Copyright (c) 2008, Xiong Yingfei, the University of Tokyo All rights
 * reserved.
 */
package ac.jp.u_tokyo.SyncLib.dictionaries;

import java.util.Arrays;

import ac.jp.u_tokyo.SyncLib.Mod;
import ac.jp.u_tokyo.SyncLib.SyncFactory;
import ac.jp.u_tokyo.SyncLib.SynchronizationFailedException;
import ac.jp.u_tokyo.SyncLib.util.Pair;

public class EqualDictMapCombinator extends DictMapCombinatorBase
{
	public EqualDictMapCombinator(SyncFactory innerSync, int dictCount,
			int nonDictCount)
	{
		super(innerSync, dictCount, nonDictCount);
	}
	
	private class EqualSynchronizationPerformer extends SynchronizationPerformer{

		public EqualSynchronizationPerformer(Mod[] modifications,
				InfoProvider provider)
		{
			super(modifications, provider);
		}

		@Override
		protected void match() throws SynchronizationFailedException
		{
			Pair<Integer, Object> unmatched;
			while ((unmatched = getFirstUnmatched(unmatchedKeys)) != null)
			{
				Object[] keys = new Object[getDictCount()];
				Arrays.fill(keys, unmatched.getValue2());
				syncMatched(keys);
			}
		}

		@Override
		protected void createNewKeysIfNecessary(Object[] selectedKeys)
		{
		}

	}

	@Override
	protected Mod[] doResynchronize(Object[] values, Mod[] modifications)
			throws SynchronizationFailedException
	{
		Mod[] result = new EqualSynchronizationPerformer(modifications, new ResyncInfoProvider(values))
				.doSynchronization();
		return result;
	}

	@Override
	protected Mod[] doSynchronize(Mod[] modifications)
			throws SynchronizationFailedException
	{
		try
		{
			Mod[] result = new EqualSynchronizationPerformer(modifications, new SyncInfoProvider())
					.doSynchronization();
			return result;
		}
		catch (SynchronizationFailedException e)
		{
			throw e;
		}
	}

	@Override
	public String toString()
	{
		return "EqualDictMapCombinator@" + hashCode();
	}

}
